from typing import Dict, Any
from langgraph.graph import StateGraph
from pydantic import BaseModel, Field
from intelli_port.data_layer.clients import mysql_execute_read


class ServiceSecurityWait(BaseModel):
    type: str = Field(default="security_wait")
    estimated_wait_min: float
    advice: str | None = None


def build_security_subgraph():
    g = StateGraph(dict)

    def security_wait(state: Dict[str, Any]) -> Dict[str, Any]:
        est = 10.0
        try:
            r = mysql_execute_read("SELECT `value` FROM kv_config WHERE `key`=%s", ("security.wait.min",), fetch="one").get("rows", [])
            if r and r[0] and r[0][0]:
                est = float(r[0][0])
        except Exception:
            est = 10.0
        advice = "高峰期请预留30分钟以上"
        try:
            ra = mysql_execute_read("SELECT `value` FROM kv_config WHERE `key`=%s", ("security.advice",), fetch="one").get("rows", [])
            if ra and ra[0] and ra[0][0]:
                advice = str(ra[0][0])
        except Exception:
            pass
        slots = state.get("slots") or {}
        if bool(slots.get("prefer_accessible") or False):
            advice = advice + "；无障碍安检通道优先" if advice else "建议走无障碍安检通道"
        svc = ServiceSecurityWait(estimated_wait_min=est, advice=advice).model_dump()
        return {**state, "service": svc}

    g.add_node("security_wait", security_wait)
    g.set_entry_point("security_wait")
    return g.compile()